<?xml version="1.0" encoding="UTF-8" ?>
<!--

    Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
    under one or more contributor license agreements. See the NOTICE file
    distributed with this work for additional information regarding copyright
    ownership. Camunda licenses this file to you under the Apache License,
    Version 2.0; you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="org.camunda.bpm.engine.impl.persistence.entity.HistoricProcessInstanceEntity">

  <resultMap id="finishedReportResultMap" type="org.camunda.bpm.engine.impl.persistence.entity.CleanableHistoricProcessInstanceReportResultEntity">
    <result property="cleanableProcessInstanceCount" column="CLEANABLE_" jdbcType="BIGINT" />
    <result property="finishedProcessInstanceCount" column="FINISHED_" jdbcType="BIGINT" />
    <result property="processDefinitionId" column="ID_" jdbcType="VARCHAR" />
    <result property="processDefinitionKey" column="KEY_" jdbcType="VARCHAR" />
    <result property="processDefinitionName" column="NAME_" jdbcType="VARCHAR" />
    <result property="processDefinitionVersion" column="VERSION_" jdbcType="VARCHAR" />
    <result property="historyTimeToLive" column="HISTORY_TTL_" jdbcType="BIGINT" />
    <result property="tenantId" column="TENANT_ID_" jdbcType="VARCHAR"/>
  </resultMap>

  <!-- HISTORIC PROCESS INSTANCE INSERT -->

  <insert id="insertHistoricProcessInstanceEvent"
          parameterType="org.camunda.bpm.engine.impl.history.event.HistoricProcessInstanceEventEntity">
    insert into ${prefix}ACT_HI_PROCINST (
      ID_,
      PROC_INST_ID_,
      BUSINESS_KEY_,
      PROC_DEF_KEY_,
      PROC_DEF_ID_,
      START_TIME_,
      END_TIME_,
      REMOVAL_TIME_,
      DURATION_,
      START_USER_ID_,
      START_ACT_ID_,
      END_ACT_ID_,
      SUPER_PROCESS_INSTANCE_ID_,
      ROOT_PROC_INST_ID_,
      SUPER_CASE_INSTANCE_ID_,
      CASE_INST_ID_,
      DELETE_REASON_,
      TENANT_ID_,
      STATE_
    ) values (
      #{id ,jdbcType=VARCHAR},
      #{processInstanceId, jdbcType=VARCHAR},
      #{businessKey, jdbcType=VARCHAR},
      #{processDefinitionKey, jdbcType=VARCHAR},
      #{processDefinitionId, jdbcType=VARCHAR},
      #{startTime, jdbcType=TIMESTAMP},
      #{endTime, jdbcType=TIMESTAMP},
      #{removalTime, jdbcType=TIMESTAMP},
      #{durationInMillis ,jdbcType=BIGINT},
      #{startUserId, jdbcType=VARCHAR},
      #{startActivityId, jdbcType=VARCHAR},
      #{endActivityId, jdbcType=VARCHAR},
      #{superProcessInstanceId, jdbcType=VARCHAR},
      #{rootProcessInstanceId, jdbcType=VARCHAR},
      #{superCaseInstanceId, jdbcType=VARCHAR},
      #{caseInstanceId, jdbcType=VARCHAR},
      #{deleteReason, jdbcType=VARCHAR},
      #{tenantId, jdbcType=VARCHAR},
      #{state, jdbcType=VARCHAR}
    )
  </insert>

  <!-- HISTORIC PROCESS INSTANCE UPDATE -->

  <update id="updateHistoricProcessInstanceEvent"
          parameterType="org.camunda.bpm.engine.impl.persistence.entity.HistoricProcessInstanceEntity">
    update ${prefix}ACT_HI_PROCINST set
    PROC_DEF_ID_ = #{processDefinitionId, jdbcType=VARCHAR},
    PROC_DEF_KEY_ = #{processDefinitionKey, jdbcType=VARCHAR},
    BUSINESS_KEY_ = #{businessKey, jdbcType=VARCHAR},
    END_ACT_ID_ = #{endActivityId, jdbcType=VARCHAR},
    DELETE_REASON_ = #{deleteReason, jdbcType=VARCHAR},
    SUPER_PROCESS_INSTANCE_ID_ = #{superProcessInstanceId, jdbcType=VARCHAR},
    STATE_ = #{state, jdbcType=VARCHAR}

    <if test="endTime!=null">
        , END_TIME_ = #{endTime, jdbcType=TIMESTAMP}
        , DURATION_ = #{durationInMillis, jdbcType=BIGINT}
    </if>

    <if test="removalTime!=null">
      , REMOVAL_TIME_ = #{removalTime, jdbcType=TIMESTAMP}
    </if>

    where ID_ = #{id, jdbcType=VARCHAR}
  </update>

  <update id="updateHistoricProcessInstanceEventsByRootProcessInstanceId"
          parameterType="java.util.Map">
    update ${prefix}ACT_HI_PROCINST set
    REMOVAL_TIME_ = #{removalTime, jdbcType=TIMESTAMP}

    where ROOT_PROC_INST_ID_ = #{rootProcessInstanceId, jdbcType=VARCHAR}
  </update>

  <update id="updateHistoricProcessInstanceEventsByRootProcessInstanceId_mssql"
          parameterType="java.util.Map">
    update RES set
    RES.REMOVAL_TIME_ = #{removalTime, jdbcType=TIMESTAMP}
    FROM ${prefix}ACT_HI_PROCINST RES WITH (FORCESEEK)
    where RES.ROOT_PROC_INST_ID_ = #{rootProcessInstanceId, jdbcType=VARCHAR}
  </update>

  <update id="updateHistoricProcessInstanceByProcessInstanceId"
          parameterType="java.util.Map">
    update ${prefix}ACT_HI_PROCINST
      set REMOVAL_TIME_ = #{removalTime, jdbcType=TIMESTAMP}
      where PROC_INST_ID_ = #{processInstanceId, jdbcType=VARCHAR}
  </update>

  <update id="updateHistoricProcessInstanceByProcessInstanceId_mssql"
          parameterType="java.util.Map">
    update RES set
    RES.REMOVAL_TIME_ = #{removalTime, jdbcType=TIMESTAMP}
    FROM ${prefix}ACT_HI_PROCINST RES WITH (FORCESEEK)
    where RES.PROC_INST_ID_ = #{processInstanceId, jdbcType=VARCHAR}
  </update>

  <!-- HISTORIC PROCESS INSTANCE SELECT -->

  <select id="selectHistoricProcessInstanceEvent" parameterType="java.lang.String"
          resultMap="historicProcessInstanceResultMap">
    select HPI.START_TIME_, HPI.REMOVAL_TIME_ from ${prefix}ACT_HI_PROCINST HPI
    where HPI.ID_ = #{id, jdbcType=VARCHAR}
  </select>

  <!-- HISTORIC PROCESS INSTANCE DELETE -->

  <delete id="deleteHistoricProcessInstance">
    delete from ${prefix}ACT_HI_PROCINST where PROC_INST_ID_ = #{processInstanceId}
  </delete>

  <delete id="deleteHistoricProcessInstances">
    delete
    from ${prefix}ACT_HI_PROCINST
    where
      <bind name="listOfIds" value="list"/>
      <bind name="fieldName" value="'PROC_INST_ID_'"/>
      <include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.applyInForPaginatedCollection"/>
  </delete>

  <delete id="deleteHistoricProcessInstancesByRemovalTime"
          parameterType="org.camunda.bpm.engine.impl.db.ListQueryParameterObject">
    <bind name="date" value="'REMOVAL_TIME_'"/>
    <bind name="reportPeriodUnitName" value="'MINUTE'"/>
    delete ${limitBeforeWithoutOffset} from ${prefix}ACT_HI_PROCINST
    where REMOVAL_TIME_ &lt;= #{parameter.removalTime}
    <include refid="andWhereMinuteInDateBetweenSql"/>
    ${limitAfterWithoutOffset}
  </delete>

  <delete id="deleteHistoricProcessInstancesByRemovalTime_oracle"
          parameterType="org.camunda.bpm.engine.impl.db.ListQueryParameterObject">
    <bind name="date" value="'REMOVAL_TIME_'"/>
    <bind name="reportPeriodUnitName" value="'MINUTE'"/>
    delete ${limitBeforeWithoutOffset} from ${prefix}ACT_HI_PROCINST
    where REMOVAL_TIME_ &lt;= #{parameter.removalTime}
    <include refid="andWhereMinuteInDateBetweenSql_oracle"/>
    ${limitAfterWithoutOffset}
  </delete>

  <delete id="deleteHistoricProcessInstancesByRemovalTime_postgres_or_db2"
          parameterType="org.camunda.bpm.engine.impl.db.ListQueryParameterObject">
    <bind name="date" value="'REMOVAL_TIME_'"/>
    <bind name="reportPeriodUnitName" value="'MINUTE'"/>
    delete ${limitBeforeWithoutOffset} from ${prefix}ACT_HI_PROCINST
    where ID_ IN
      (SELECT ID_
       FROM ${prefix}ACT_HI_PROCINST
       WHERE REMOVAL_TIME_ &lt;= #{parameter.removalTime} <include refid="andWhereMinuteInDateBetweenSql"/>
       ${limitAfterWithoutOffset})
  </delete>

  <!-- HISTORIC PROCESS INSTANCE RESULT MAP -->

  <resultMap id="historicProcessInstanceResultMap"
             type="org.camunda.bpm.engine.impl.persistence.entity.HistoricProcessInstanceEntity">
    <id property="id" column="ID_" jdbcType="VARCHAR"/>
    <result property="processInstanceId" column="PROC_INST_ID_" jdbcType="VARCHAR"/>
    <result property="businessKey" column="BUSINESS_KEY_" jdbcType="VARCHAR"/>
    <result property="processDefinitionKey" column="PROC_DEF_KEY_" jdbcType="VARCHAR"/>
    <result property="processDefinitionId" column="PROC_DEF_ID_" jdbcType="VARCHAR"/>
    <result property="processDefinitionName" column="NAME_" jdbcType="VARCHAR"/>
    <result property="processDefinitionVersion" column="VERSION_" jdbcType="INTEGER"/>
    <result property="startTime" column="START_TIME_" jdbcType="TIMESTAMP"/>
    <result property="endTime" column="END_TIME_" jdbcType="TIMESTAMP"/>
    <result property="removalTime" column="REMOVAL_TIME_" jdbcType="TIMESTAMP"/>
    <result property="durationInMillis" column="DURATION_" jdbcType="BIGINT"/>
    <result property="startUserId" column="START_USER_ID_" jdbcType="VARCHAR"/>
    <result property="startActivityId" column="START_ACT_ID_" jdbcType="VARCHAR"/>
    <result property="endActivityId" column="END_ACT_ID_" jdbcType="VARCHAR"/>
    <result property="superProcessInstanceId" column="SUPER_PROCESS_INSTANCE_ID_" jdbcType="VARCHAR"/>
    <result property="rootProcessInstanceId" column="ROOT_PROC_INST_ID_" jdbcType="VARCHAR"/>
    <result property="superCaseInstanceId" column="SUPER_CASE_INSTANCE_ID_" jdbcType="VARCHAR"/>
    <result property="caseInstanceId" column="CASE_INST_ID_" jdbcType="VARCHAR"/>
    <result property="deleteReason" column="DELETE_REASON_" jdbcType="VARCHAR"/>
    <result property="tenantId" column="TENANT_ID_" jdbcType="VARCHAR"/>
    <result property="state" column="STATE_" jdbcType="VARCHAR"/>
  </resultMap>
  
  <resultMap type="org.camunda.bpm.engine.impl.util.ImmutablePair" id="deploymentIdMapping">
    <id property="left" column="DEPLOYMENT_ID_" jdbcType="VARCHAR" />
    <id property="right" column="ID_" jdbcType="VARCHAR" />
  </resultMap>

  <!-- HISTORIC PROCESS INSTANCE SELECT -->

  <select id="selectHistoricProcessInstance" resultMap="historicProcessInstanceResultMap">
    select * from ${prefix}ACT_HI_PROCINST where PROC_INST_ID_ = #{processInstanceId}
  </select>

  <select id="selectHistoricProcessInstanceIdsByProcessDefinitionId"
            parameterType="org.camunda.bpm.engine.impl.db.ListQueryParameterObject" resultType="string">
    select ID_
    from ${prefix}ACT_HI_PROCINST
    where PROC_DEF_ID_ = #{parameter}
  </select>

  <select id="selectHistoricProcessInstancesByQueryCriteria"
          parameterType="org.camunda.bpm.engine.impl.HistoricProcessInstanceQueryImpl"
          resultMap="historicProcessInstanceResultMap">
    <include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.bindOrderBy"/>
    ${limitBefore}
    select ${distinct} RES.*
    ${limitBetween}
    <include refid="selectHistoricProcessInstancesByQueryCriteriaSql"/>
    ${orderBy}
    ${limitAfter}
  </select>

  <select id="selectHistoricProcessInstanceIdsByQueryCriteria"
          parameterType="org.camunda.bpm.engine.impl.HistoricProcessInstanceQueryImpl"
          resultType="string">
    <include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.bindOrderBy"/>
    ${limitBefore}
    select ${distinct} RES.ID_
    ${limitBetween}
    <include refid="selectHistoricProcessInstancesByQueryCriteriaSql"/>
    ${orderBy}
    ${limitAfter}
  </select>

  <select id="selectHistoricProcessInstanceCountByQueryCriteria"
          parameterType="org.camunda.bpm.engine.impl.HistoricProcessInstanceQueryImpl" resultType="long">
    ${countDistinctBeforeStart} RES.ID_ ${countDistinctBeforeEnd}
    <include refid="selectHistoricProcessInstancesByQueryCriteriaSql"/>
    ${countDistinctAfterEnd}
  </select>
  
  <select id="selectHistoricProcessInstanceDeploymentIdMappingsByQueryCriteria" parameterType="org.camunda.bpm.engine.impl.HistoricProcessInstanceQueryImpl" resultMap="deploymentIdMapping">
    select distinct RES.DEPLOYMENT_ID_, RES.ID_
    <include refid="selectHistoricProcessInstancesByQueryCriteriaSql"/>
    ORDER BY RES.DEPLOYMENT_ID_ ASC
  </select>

  <sql id="selectHistoricProcessInstancesByQueryCriteriaSql">

    from (

    SELECT SELF.*, DEF.NAME_, DEF.VERSION_, DEF.DEPLOYMENT_ID_
    FROM ${prefix}ACT_HI_PROCINST SELF

    LEFT JOIN ${prefix}ACT_RE_PROCDEF DEF
    ON SELF.PROC_DEF_ID_ = DEF.ID_


    <if test="authCheck.shouldPerformAuthorizatioCheck &amp;&amp; !authCheck.revokeAuthorizationCheckEnabled &amp;&amp; authCheck.authUserId != null">
        <!--
          HEADS-UP!!!
          If you change something here, you should probably also change it the EE Webapp
          See camunda-bpm-platform-ee/webapps/camunda-webapp/plugins/src/main/resources/org/camunda/bpm/cockpit/impl/plugin/history/historicProcessInstance.xml
        -->
        <include refid="org.camunda.bpm.engine.impl.persistence.entity.AuthorizationEntity.authCheckJoinWithoutOnClause"/>
        AUTH ON (AUTH.RESOURCE_ID_ ${authJoinStart}
          SELF.PROC_DEF_KEY_ ${authJoinSeparator} '*'
          <if test="authCheck.isHistoricInstancePermissionsEnabled">
            ${authJoinSeparator} SELF.ID_
          </if>
          ${authJoinEnd}
        )
    </if>

    <bind name="INC_JOIN" value="false" />
    <bind name="HAI_JOIN" value="false" />
    <bind name="JOIN_TYPE" value="'inner join'" />

    <foreach collection="queries" item="query">
      <if test="query.isOrQueryActive">
        <bind name="JOIN_TYPE" value="'left join'" />
      </if>

      <if test="query != null &amp;&amp; (query.withIncidents || query.withRootIncidents || query.incidentStatus != null || query.incidentMessage != null || query.incidentMessageLike != null || query.incidentType != null)">
        <bind name="INC_JOIN" value="true" />
      </if>

      <if test="query != null &amp;&amp; (query.executedActivityIds != null and query.executedActivityIds.length > 0) || (query.activeActivityIds != null and query.activeActivityIds.length > 0)">
        <bind name="HAI_JOIN" value="true" />
      </if>
    </foreach>

    <if test="INC_JOIN">
      ${JOIN_TYPE} ${prefix}ACT_HI_INCIDENT INC on SELF.PROC_INST_ID_ = INC.PROC_INST_ID_
    </if>
    <if test="HAI_JOIN">
      LEFT JOIN ${prefix}ACT_HI_ACTINST HAI
      ON HAI.PROC_INST_ID_ = SELF.ID_
    </if>
    
    <!-- actual value conditions are checked in the WHERE part; 
       however here we must join once for every variable condition.
       It is important that in the WHERE part we use the same table
       names for the respective conditions (i.e. VI0, VI1, VI2, ...) -->
    <bind name="variableConditionCounter" value="0" />
    <foreach collection="queries" item="query">
      <foreach collection="query.queryVariableNameToValuesMap">
        LEFT JOIN ${prefix}ACT_HI_VARINST VI${variableConditionCounter}
        ON SELF.PROC_INST_ID_ = VI${variableConditionCounter}.PROC_INST_ID_
        <bind name="variableConditionCounter" value="variableConditionCounter + 1" />
      </foreach>
    </foreach>

    <bind name="variableConditionCounter" value="0" />
    <where>
      <foreach collection="queries" item="query" index="i">
        <choose>
          <when test="i == 0">
            <bind name="queryType" value="'and'" />
          </when>
          <otherwise>
            <bind name="queryType" value="'or'" />
          </otherwise>
        </choose>
        and (
        <trim suffixOverrides="and">
          1 = 1 and
          <trim prefixOverrides="or|and">
            <if test="query.processInstanceId != null">
              ${queryType} SELF.PROC_INST_ID_ = #{query.processInstanceId}
            </if>
            <if test="query.processInstanceIds != null and !query.processInstanceIds.isEmpty()">
              ${queryType}
              <bind name="listOfIds" value="query.processInstanceIds" />
              <bind name="fieldName" value="'SELF.PROC_INST_ID_'" />
              <include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.applyInForPaginatedCollection" />
            </if>
            <if test="query.caseInstanceId != null">
              ${queryType} SELF.CASE_INST_ID_ = #{query.caseInstanceId}
            </if>
            <if test="query.processDefinitionId != null">
              ${queryType} SELF.PROC_DEF_ID_ = #{query.processDefinitionId}
            </if>
            <if test="query.processDefinitionKey != null">
              ${queryType} DEF.KEY_ = #{query.processDefinitionKey}
            </if>
            <if test="query.processDefinitionKeys != null &amp;&amp; query.processDefinitionKeys.length > 0">
              and DEF.KEY_ in
              <foreach item="item" index="index" collection="query.processDefinitionKeys"
                       open="(" separator="," close=")">
                #{item}
              </foreach>
            </if>
            <if test="query.processDefinitionName != null">
              ${queryType} DEF.NAME_ = #{query.processDefinitionName}
            </if>
            <if test="query.processDefinitionNameLike != null">
              ${queryType} DEF.NAME_ like #{query.processDefinitionNameLike} ESCAPE ${escapeChar}
            </if>
            <if test="query.businessKey != null">
              ${queryType} SELF.BUSINESS_KEY_ = #{query.businessKey}
            </if>
            <if test="query.businessKeyIn != null">
              ${queryType} SELF.BUSINESS_KEY_ in
              <foreach item="item" index="index" collection="query.businessKeyIn"
                       open="(" separator="," close=")">
                #{item}
              </foreach>
            </if>
            <if test="query.businessKeyLike != null">
              ${queryType} SELF.BUSINESS_KEY_ like #{query.businessKeyLike} ESCAPE ${escapeChar}
            </if>

            <if test="query.startedBefore != null">
              ${queryType} SELF.START_TIME_ &lt;= #{query.startedBefore}
            </if>
            <if test="query.startedAfter != null">
              ${queryType} SELF.START_TIME_ &gt;= #{query.startedAfter}
            </if>
            <if test="query.finishedBefore != null">
              ${queryType} SELF.END_TIME_ &lt;= #{query.finishedBefore}
            </if>
            <if test="query.finishedAfter != null">
              ${queryType} SELF.END_TIME_ &gt;= #{query.finishedAfter}
            </if>
            <if test="query.processKeyNotIn != null">
              ${queryType} (
                <foreach collection="query.processKeyNotIn" index="index" item="procDefKey"
                         open="(" separator=" and " close=")">
                  DEF.KEY_ not like #{procDefKey} ESCAPE ${escapeChar}
                </foreach>
              )
            </if>
            <if test="query.state != null">
              ${queryType} SELF.STATE_ = #{query.state}
            </if>


            <!-- DEPRECATED : TO BE REMOVED IN 5.11 -->
            <if test="query.startDateOn">
              ${queryType} (SELF.START_TIME_ &gt;= #{query.startDateOnBegin}
              and SELF.START_TIME_ &lt;= #{query.startDateOnEnd})
            </if>
            <!-- DEPRECATED : TO BE REMOVED IN 5.11 -->
            <if test="query.finishDateOn">
              ${queryType} (SELF.END_TIME_ &gt;= #{query.finishDateOnBegin}
              and SELF.END_TIME_ &lt;= #{query.finishDateOnEnd})
            </if>
            <!-- DEPRECATED : TO BE REMOVED IN 5.11 -->
            <if test="query.finishDateBy">
              ${queryType} SELF.END_TIME_ &lt;= #{query.finishDateBy}
            </if>
            <!-- DEPRECATED : TO BE REMOVED IN 5.11 -->
            <if test="query.startDateBy">
              ${queryType} SELF.START_TIME_ &gt;= #{query.startDateBy}
            </if>

            <if test="query.unfinished">
              ${queryType} SELF.END_TIME_ IS NULL
            </if>
            <if test="query.finished">
              ${queryType} SELF.END_TIME_ is not NULL
            </if>

            <if test="query.incidentType != null">
              ${queryType} INC.INCIDENT_TYPE_ = #{query.incidentType}
            </if>
            <if test="query.incidentMessage != null">
              ${queryType} INC.INCIDENT_MSG_ = #{query.incidentMessage}
            </if>

            <if test="query.incidentMessageLike != null">
              ${queryType} INC.INCIDENT_MSG_ like #{query.incidentMessageLike} ESCAPE ${escapeChar}
            </if>

            <if test="query.incidentStatus == 'open'">
              ${queryType} INC.END_TIME_ is null
            </if>

            <if test="query.incidentStatus == 'resolved'">
              ${queryType} INC.END_TIME_ is not null
            </if>

            <if test="query.withRootIncidents">
              ${queryType} INC.ID_ = INC.ROOT_CAUSE_INCIDENT_ID_
            </if>
            <if test="query.startedBy != null">
              ${queryType} SELF.START_USER_ID_ = #{query.startedBy}
            </if>

            <if test="query.isRootProcessInstances">
              ${queryType} SELF.SUPER_PROCESS_INSTANCE_ID_ is null
            </if>
            <if test="query.superProcessInstanceId != null">
              ${queryType} SELF.SUPER_PROCESS_INSTANCE_ID_ = #{query.superProcessInstanceId}
            </if>
            <if test="query.subProcessInstanceId != null">
              ${queryType} SELF.PROC_INST_ID_ = (select SUPER_PROCESS_INSTANCE_ID_ from ${prefix}ACT_HI_PROCINST where
              PROC_INST_ID_ = #{query.subProcessInstanceId})
            </if>
            <if test="query.superCaseInstanceId != null">
              ${queryType} SELF.SUPER_CASE_INSTANCE_ID_ = #{query.superCaseInstanceId}
            </if>
            <if test="query.subCaseInstanceId != null">
              ${queryType} SELF.PROC_INST_ID_ = (select SUPER_PROCESS_INSTANCE_ID_ from ${prefix}ACT_HI_CASEINST where
              CASE_INST_ID_ = #{query.subCaseInstanceId})
            </if>
            <foreach collection="query.queryVariableNameToValuesMap" item="queryVariableValues">
              <bind name="varPrefix" value="'VI' + variableConditionCounter + '.'"/>
              <foreach collection="queryVariableValues" item="queryVariableValue">
                ${queryType} (${varPrefix}ID_ IS NOT NULL
                AND

                <include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.variableNameEqualsCaseInsensitive" />

                <bind name="varTypeField" value="'VAR_TYPE_'"/>
                <if test="queryVariableValue.valueConditions != null">
                  and <include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.variableValueConditions"/>
                </if>
                )
              </foreach>
              <bind name="variableConditionCounter" value="variableConditionCounter + 1" />
            </foreach>

            <if test="query.executedActivityAfter != null || query.executedActivityBefore != null">
              ${queryType} EXISTS (
              SELECT *
              FROM ${prefix}ACT_HI_ACTINST
              <where>
                PROC_INST_ID_ = SELF.ID_
                <if test="query.executedActivityAfter != null">
                  AND (START_TIME_ &gt;= #{query.executedActivityAfter} OR END_TIME_ &gt;= #{query.executedActivityAfter})
                </if>
                <if test="query.executedActivityBefore != null">
                  AND (START_TIME_ &lt;= #{query.executedActivityBefore} OR END_TIME_ &lt;= #{query.executedActivityBefore})
                </if>
              </where>
              )
            </if>

            <if test="query.executedActivityIds != null and query.executedActivityIds.length > 0">
              ${queryType} (
                HAI.END_TIME_ IS NOT NULL
                AND HAI.ACT_ID_ IN
                <foreach item="activityId" index="index" collection="query.executedActivityIds" open="(" separator="," close=")">
                  #{activityId}
                </foreach>
              )
            </if>

            <if test="query.activeActivityIds != null and query.activeActivityIds.length > 0">
              ${queryType} (
                HAI.END_TIME_ IS NULL
                AND HAI.ACT_ID_ IN
                <foreach item="activityId" index="index" collection="query.activeActivityIds" open="(" separator="," close=")">
                  #{activityId}
                </foreach>
              )
            </if>

            <if test="query.executedJobAfter != null || query.executedJobBefore != null">
              ${queryType} EXISTS (
              SELECT *
              FROM ${prefix}ACT_HI_JOB_LOG
              <where>
                PROCESS_INSTANCE_ID_ = SELF.ID_
                <if test="query.executedJobAfter != null">
                  AND TIMESTAMP_ &gt;= #{query.executedJobAfter}
                </if>
                <if test="query.executedJobBefore != null">
                  AND TIMESTAMP_ &lt;= #{query.executedJobBefore}
                </if>
              </where>
              )
            </if>

            <if test="query.isTenantIdSet">
              <if test="query.tenantIds != null &amp;&amp; query.tenantIds.length > 0">
                ${queryType} SELF.TENANT_ID_ in
                <foreach item="tenantId" index="index" collection="query.tenantIds"
                         open="(" separator="," close=")">
                  #{tenantId}
                </foreach>
              </if>
              <if test="query.tenantIds == null">
                ${queryType} SELF.TENANT_ID_ is null
              </if>
            </if>
          </trim>
        </trim>
        )
      </foreach>

      <if test="authCheck.shouldPerformAuthorizatioCheck &amp;&amp; authCheck.authUserId != null">
        <!--
          HEADS-UP!!!
          If you change something here, you should probably also change it the EE Webapp
          See camunda-bpm-platform-ee/webapps/camunda-webapp/plugins/src/main/resources/org/camunda/bpm/cockpit/impl/plugin/history/historicProcessInstance.xml
        -->
        and (
        (SELF.PROC_DEF_KEY_ is not null
        <include refid="org.camunda.bpm.engine.impl.persistence.entity.AuthorizationEntity.queryAuthorizationCheck"/>
        ) or SELF.PROC_DEF_KEY_ is null
        )
      </if>

      <include refid="org.camunda.bpm.engine.impl.persistence.entity.TenantEntity.queryTenantCheckWithSelfPrefix"/>
    </where>

    ) RES

  </sql>

  <select id="selectHistoricProcessInstanceByNativeQuery" parameterType="java.util.Map"
          resultMap="historicProcessInstanceResultMap">
    <if test="resultType == 'LIST_PAGE'">
        ${limitBefore}
    </if>
    ${sql}
    <if test="resultType == 'LIST_PAGE'">
        ${limitAfter}
    </if>
  </select>

  <!-- Select ids for async history cleanup -->
  <sql id="selectHistoricProcessInstanceIdsForCleanupSql">
    <bind name="days" value="'pd.HISTORY_TTL_'"/>
    <bind name="date" value="'pi.END_TIME_'"/>
    <bind name="currentTimestamp" value="parameter.currentTimestamp"/>
    <bind name="reportPeriodUnitName" value="'MINUTE'"/>
    FROM ${prefix}ACT_HI_PROCINST pi, ${prefix}ACT_RE_PROCDEF pd
    where
        pi.PROC_DEF_ID_ = pd.ID_
        AND not pi.END_TIME_ is NULL
        AND not pd.HISTORY_TTL_ is NULL
        AND ${dayComparator}
  </sql>

  <sql id="andWhereMinuteInDateBetweenSql">
    <if test="parameter.minuteFrom != null and parameter.minuteTo != null">
      AND ${datepart1}<include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.periodUnitFunction"/>${datepart2}${date}${datepart3}
      between #{parameter.minuteFrom, jdbcType=INTEGER} and #{parameter.minuteTo, jdbcType=INTEGER}
    </if>
  </sql>

  <sql id="andWhereMinuteInDateBetweenSql_oracle">
    <if test="parameter.minuteFrom != null and parameter.minuteTo != null">
      AND ${datepart1}${date}${datepart2}<include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.periodUnitFunction"/>${datepart3}
      between #{parameter.minuteFrom, jdbcType=INTEGER} and #{parameter.minuteTo, jdbcType=INTEGER}
    </if>
  </sql>

  <select id="selectHistoricProcessInstanceIdsForCleanup" parameterType="org.camunda.bpm.engine.impl.db.ListQueryParameterObject" resultType="string">
    SELECT ${limitBeforeWithoutOffset} pi.PROC_INST_ID_, pi.END_TIME_
    <include refid="selectHistoricProcessInstanceIdsForCleanupSql"/>
    <include refid="andWhereMinuteInDateBetweenSql"/>
    ${limitAfterWithoutOffset}
  </select>

  <select id="selectHistoricProcessInstanceIdsForCleanup_oracle" parameterType="org.camunda.bpm.engine.impl.db.ListQueryParameterObject" resultType="string">
    SELECT /*+ FIRST_ROWS(${maxResults}) NO_PARALLEL(pi) NO_PARALLEL(pd) */ pi.PROC_INST_ID_, pi.END_TIME_
    <include refid="selectHistoricProcessInstanceIdsForCleanupSql"/>
    <include refid="andWhereMinuteInDateBetweenSql_oracle"/>
    ${limitAfterWithoutOffset}
  </select>

  <!-- DB2 or MSSQL -->
  <select id="selectHistoricProcessInstanceByNativeQuery_mssql_or_db2" parameterType="java.util.Map"
          resultMap="historicProcessInstanceResultMap">
    <if test="resultType == 'LIST_PAGE'">
      ${limitBeforeNativeQuery}
    </if>
    ${sql}
    <if test="resultType == 'LIST_PAGE'">
      ${limitAfter}
    </if>
  </select>

  <select id="selectHistoricProcessInstanceCountByNativeQuery" parameterType="java.util.Map" resultType="long">
    ${sql}
  </select>

  <!-- Select History Cleanup Report Entities -->
  <select id="selectFinishedProcessInstancesReportEntitiesCount" parameterType="org.camunda.bpm.engine.impl.CleanableHistoricProcessInstanceReportImpl" resultType="long">
    ${countDistinctBeforeStart} RES.ID_ ${countDistinctBeforeEnd}
    <include refid="selectFinishedProcessInstancesReportEntitiesSql" />
    ${countDistinctAfterEnd}
  </select>

  <select id="selectFinishedProcessInstancesReportEntities" parameterType="org.camunda.bpm.engine.impl.CleanableHistoricProcessInstanceReportImpl" resultMap="finishedReportResultMap">
    <include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.bindOrderBy"/>
    ${limitBefore}
    SELECT ${distinct} RES.*
    ${limitBetween}
    <include refid="selectFinishedProcessInstancesReportEntitiesSql"/>
    ${orderBy}
    ${limitAfter}
  </select>

  <sql id="selectFinishedProcessInstancesReportEntitiesSql">
    <bind name="days" value="'RES.HISTORY_TTL_'"/>
    <bind name="date" value="'PI.END_TIME_'"/>

    FROM (

      SELECT RES.ID_,
        RES.KEY_,
        RES.NAME_,
        RES.VERSION_,
        RES.HISTORY_TTL_,
        RES.TENANT_ID_,
        F.FINISHED_,
        <choose>
          <when test="isHistoryCleanupStrategyRemovalTimeBased">
            SUM(CASE WHEN PI.REMOVAL_TIME_ is not null and PI.REMOVAL_TIME_ &lt;= #{currentTimestamp} THEN 1 ELSE 0 END) AS CLEANABLE_
          </when>
          <otherwise>
            SUM(CASE WHEN RES.HISTORY_TTL_ is not null and PI.END_TIME_ is not null and (RES.HISTORY_TTL_ = 0 OR ${dayComparator}) THEN 1 ELSE 0 END) AS CLEANABLE_
          </otherwise>
        </choose>
      FROM
        (
          SELECT DISTINCT RES.*
          FROM ${prefix}ACT_RE_PROCDEF RES
          <if test="authCheck.shouldPerformAuthorizatioCheck &amp;&amp; !authCheck.revokeAuthorizationCheckEnabled &amp;&amp; authCheck.authUserId != null">
            <include refid="org.camunda.bpm.engine.impl.persistence.entity.AuthorizationEntity.authCheckJoinWithoutOnClause" />
            AUTH ON (AUTH.RESOURCE_ID_ ${authJoinStart} RES.KEY_ ${authJoinSeparator} '*' ${authJoinEnd})
          </if>
          <where>

            <if test="processDefinitionIdIn != null &amp;&amp; processDefinitionIdIn.length > 0">
              RES.ID_ IN
              <foreach item="processInstanceId" index="index" collection="processDefinitionIdIn" open="(" separator="," close=")">
                  #{processInstanceId}
              </foreach>
            </if>

            <if test="processDefinitionKeyIn != null &amp;&amp; processDefinitionKeyIn.length > 0">
              and RES.KEY_ IN
              <foreach item="processInstanceKey" index="index" collection="processDefinitionKeyIn" open="(" separator="," close=")">
                  #{processInstanceKey}
              </foreach>
            </if>

            <if test="isTenantIdSet">
              <if test="tenantIdIn != null &amp;&amp; tenantIdIn.length > 0">
                and RES.TENANT_ID_ in
                <foreach item="tenantId" index="index" collection="tenantIdIn"
                         open="(" separator="," close=")">
                  #{tenantId}
                </foreach>
              </if>
              <if test="tenantIdIn == null">
                and RES.TENANT_ID_ is null
              </if>
            </if>

            <include refid="org.camunda.bpm.engine.impl.persistence.entity.AuthorizationEntity.queryAuthorizationCheck" />
            <include refid="org.camunda.bpm.engine.impl.persistence.entity.TenantEntity.queryTenantCheck" />

          </where>
        ) RES
        LEFT JOIN ${prefix}ACT_HI_PROCINST PI
        ON PI.PROC_DEF_ID_ = RES.ID_
        LEFT JOIN (
          SELECT COUNT(PI.ID_) AS FINISHED_, PI.PROC_DEF_ID_
          FROM ${prefix}ACT_HI_PROCINST PI
          WHERE PI.END_TIME_ IS NOT NULL
          GROUP BY PI.PROC_DEF_ID_
          ) F ON F.PROC_DEF_ID_ = PI.PROC_DEF_ID_

        GROUP BY RES.ID_,
          RES.KEY_,
          RES.NAME_,
          RES.VERSION_,
          RES.HISTORY_TTL_,
          RES.TENANT_ID_,
          F.FINISHED_

    ) RES
    <choose>
      <when test="isCompact &amp;&amp; isHistoryCleanupStrategyRemovalTimeBased">
        WHERE (RES.CLEANABLE_ > 0 OR FINISHED_ > 0)
      </when>
      <when test="isCompact &amp;&amp; !isHistoryCleanupStrategyRemovalTimeBased">
        WHERE FINISHED_ > 0
      </when>
    </choose>

  </sql>

  <select id="selectCompletedHistoricProcessInstancePage" resultMap="historicProcessInstanceResultMap" parameterType="java.util.Map" >
    <bind name="maxResults" value="parameter.maxResults" />

    select RES.*
    from (
      ${optimizeLimitBeforeWithoutOffset}
      SELECT ${limitBeforeWithoutOffset} SELF.*, DEF.NAME_, DEF.VERSION_
      FROM ${prefix}ACT_HI_PROCINST SELF

      LEFT JOIN ${prefix}ACT_RE_PROCDEF DEF
      ON SELF.PROC_DEF_ID_ = DEF.ID_

      <where>
        <if test="parameter.finishedAfter != null">
          and SELF.END_TIME_ &gt; #{parameter.finishedAfter}
        </if>
        <if test="test=parameter.finishedAt != null">
          and SELF.END_TIME_ = #{parameter.finishedAt}
        </if>
        <if test="parameter.finishedAfter == null and parameter.finishedAt == null">
          and SELF.END_TIME_ is not null
        </if>
      </where>

      ORDER BY SELF.END_TIME_ ASC
      ${optimizeLimitAfterWithoutOffset}
    ) RES

  </select>

  <select id="selectRunningHistoricProcessInstancePage" resultMap="historicProcessInstanceResultMap" parameterType="java.util.Map" >
    <bind name="maxResults" value="parameter.maxResults" />
    select RES.*
    from (
      ${optimizeLimitBeforeWithoutOffset}
      SELECT ${limitBeforeWithoutOffset} SELF.*, DEF.NAME_, DEF.VERSION_
      FROM ${prefix}ACT_HI_PROCINST SELF

      LEFT JOIN ${prefix}ACT_RE_PROCDEF DEF
      ON SELF.PROC_DEF_ID_ = DEF.ID_

      <where>
        <if test="parameter.startedAfter != null">
          and SELF.START_TIME_ &gt; #{parameter.startedAfter}
        </if>
        <if test="test=parameter.startedAt != null">
          and SELF.START_TIME_ = #{parameter.startedAt}
        </if>
        and SELF.END_TIME_ is null
      </where>

      ORDER BY SELF.START_TIME_ ASC
      ${optimizeLimitAfterWithoutOffset}

    ) RES

  </select>

</mapper>
